<?php

namespace App\Http\Controllers;

use App\CodeResponse;
use App\VerifyRequestInput;

class BaseController extends Controller
{
    use VerifyRequestInput;

    public function __construct()
    {

    }

    /**
     * 返回数据封装
     * @param  array  $codeResponse
     * @param  null  $data
     * @param  string  $info
     * @return \Illuminate\Http\JsonResponse
     */
    private function codeReturn(array $codeResponse, $data = null, $info = '')
    {
        list($code, $message) = $codeResponse;
        $ret = ['errno' => $code, 'errmsg' => $info ?: $message];
        if (!is_null($data)) {
            if (is_array($data)) {
                $data = array_filter($data, function ($item) {
                    return $item !== null;
                });//去除掉数组里的null值
            }
            $ret['data'] = $data;
        }
        return response()->json($ret)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }

    /**
     * 成功返回
     * @param  null  $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function success($data = null)
    {
        return $this->codeReturn(CodeResponse::SUCCESS,$data);
    }

    /**
     * 失败返回
     * @param  array  $codeResponse
     * @param  string  $info
     * @return \Illuminate\Http\JsonResponse
     */
    public function fail(array $codeResponse = CodeResponse::FAIL,$info = ''){
        return $this->codeReturn($codeResponse,null,$info);
    }
}
